﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Security;
using System.Text;
using System.Reflection;
using System.Net;
using Lib.Utils;

namespace Lib.Com
{
    public class WebCom
    {
        public delegate void QueryDoneHandler(QueryResult result);
        public event QueryDoneHandler QueryDone;

        public class QueryResult
        {
            public string url { get; set; }
            public string serial { get; set; }
            public string keyCode { get; set; }
            public string ver { get; set; }
            public string passKey { get; set; }
            public string dbname { get; set; }
            public string usname { get; set; }
            public string dbpass { get; set; }
            public string UrlDownload { get; set; }
            public bool KeyValidate { get; set; }
            public string Error { get; set; }
        }

        public void Query(QueryResult result)
        {
            try
            {
                string str = result.serial + "?" + result.keyCode + "?" + result.ver + "?" + result.dbname + "?" + result.usname + "?" + result.dbpass;

                str = Cvert.StringToHex(Utils.MD5.Encrypt(str, true, result.passKey));
                str += "," + result.passKey;

                HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(result.url + str);
                fileReq.GetResponse();

                string res = fileReq.Address.Query.ToLower();
                res = res.Replace("?ret=", "");

                if (Is.IsNullOrEmpty(res)) return;
                if (res.Length > 4 && res.Trim().Substring(0, 5).ToLower() == "error")
                    result.Error = res;
                else
                {
                    string[] arr = res.Split('?');

                    result.KeyValidate = Cvert.ToBoolean(arr[0], true);
                    result.keyCode = arr[1];
                    result.UrlDownload = arr[2];
                }
                //if (!Is.IsNullOrEmpty(KeyCode))
                //{
                //    //Update database
                //}

                //if (Update.ToLower() != "no")//Update avaiable
                //{
                //    //Start download update
                //}

                //if (!Is.IsNullOrEmpty(KeyValidate) && KeyValidate.ToLower() == "no")
                //{
                //    //process key is invalidate
                //}

                if (QueryDone != null)
                    QueryDone(result);
            }
            catch (Exception ex)
            {
                result.Error = ex.Message;
            }
        }
    }
}
